const sqlite3 = require('sqlite3').verbose();

const DATABASE_PATH = 'D:/Project/React/mtalk_desk/src/assets/db/mtalk-database.db';

function openDb() {
    return new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
        if (err) {
            console.error('Error opening database:', err.message);
        }
    });
}


async function selectDeviceList() {
    return new Promise((resolve, reject) => {
        const db = openDb();

        db.all('SELECT * FROM device_list', (err, rows) => {
            if (err) {
                reject(err);
            } else {
                resolve(rows);
            }
        });

        db.close();
    });
}

async function insertDevice(device) {
    return new Promise((resolve, reject) => {
        const db = openDb();

        db.run('INSERT INTO device_list (device_id, name, ip, port, status) VALUES (?, ?, ?, ?, ?)',
            [device.device_id, device.name, device.ip, device.port, device.status],
            function (err) {
                if (err) {
                    reject(err);
                } else {
                    resolve(this.lastID);
                }
           });
    })
}